﻿using System.Windows;
using Microsoft.Phone.Scheduler;
using System;
using MVBuddy.Common.Helpers;
using MVBuddy.Common.Model;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using System.Linq;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.Collections.Generic;
using MVBuddy.Common.Resources;

namespace MVBuddy.TaskAgent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;
        public readonly static string TaskName = "MVBuddy.TaskAgent";

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override async void OnInvoke(ScheduledTask task)
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(async () =>
            {
                UserData savedData = StorageManager.LoadAppSetting<UserData>("UserData");

                HtmlRequest loginRequest = new HtmlRequest(new Uri("http://m.mediavida.com/login.php"), "POST", "application/x-www-form-urlencoded", new Dictionary<string, string>()
                    {
                        { "name", savedData.Username },
                        { "password", savedData.Password },
                    });

                HtmlDocument document = await loginRequest.DoRequest();

                if (document != null)
                {
                    NotificationData notificationData = NotificationData.FromHtmlDocument(document);

                    if (notificationData != null)
                    {
                        if (notificationData.FavoriteCount > savedData.NotificationData.FavoriteCount ||
                            notificationData.MessageCount > savedData.NotificationData.MessageCount ||
                            notificationData.NotificationCount > savedData.NotificationData.NotificationCount)
                        {
                            ShellToast toast = new ShellToast();
                            toast.NavigationUri = new Uri("/View/InfoPage.xaml", UriKind.Relative);
                            toast.Title = AppResources.AppName;
                            toast.Content = AppResources.ToastPendingNotifications;
                            toast.Show();
                        }

                        savedData.NotificationData = notificationData;

                        StorageManager.SaveAppSetting("UserData", savedData);

                        if (ShellTile.ActiveTiles.ToList().Count >= 1)
                        {
                            ShellTile tile = ShellTile.ActiveTiles.ElementAtOrDefault(0);
                            string tilePath = "/Shared/ShellContent/TileBackBackground.jpg";

                            WriteableBitmap backBitmap = savedData.RenderUserDataForBackgroundTile();
                            StorageManager.SaveShellBitmapAsJpeg(tilePath, backBitmap);

                            tile.Update(new StandardTileData()
                            {
                                BackTitle = string.Empty,
                                Count = savedData.NotificationData.NotificationCount + savedData.NotificationData.FavoriteCount + savedData.NotificationData.MessageCount,
                                BackContent = string.Empty,
                                BackBackgroundImage = new Uri("isostore:" + tilePath, UriKind.Absolute),
                            });
                        }
                    }
                    else
                    {
                        ShellToast toast = new ShellToast();
                        toast.NavigationUri = new Uri("/View/MainPage.xaml", UriKind.Relative);
                        toast.Title = AppResources.AppName;
                        toast.Content = AppResources.ToastErrorUpdating;
                        toast.Show();

                        savedData.Username = string.Empty;
                        savedData.Password = string.Empty;
                        savedData.SaveLogin = false;

                        StorageManager.SaveAppSetting("UserData", savedData);

                        Abort();

                        return;
                    }
                }

                NotifyComplete();
            });
        }
    }
}